/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mdnsapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;

/**
 *
 * @author Qaisar
 */
public class ConfigEditor {
String fileName;
ConfigEditor(String filename)
{
this.fileName = filename;

}
    void updateGateway(String ip,String port) {
    updateLineInFile("../config/dht.cfg","gateway","gateway   "+ip+":"+port);

    }

    void updateNode(String ip,String port) {
        InetAddress local = null;
        try {
            local = InetAddress.getLocalHost();
        } catch (Exception ex) {
        }
        updateLineInFile("../config/dht.cfg","node_id", "node_id  " + local.getHostAddress() + ":" + port);
    }

    public void updateLineInFile(String file, String oldLine, String newLine) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            //Construct the new file that will later be renamed to the original filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            //Read from the original file and write to the new
            //unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (line.trim().startsWith(oldLine)) {
                    pw.println(newLine);
                } else {
                    pw.println(line);
                }
                pw.flush();
            }
            pw.close();
            br.close();

            //Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            //Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile)) {
                System.out.println("Could not rename file");
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
